package com.wx.house.manager.api.permission.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.wx.house.manager.api.permission.text.RoleAddPame;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.wx.house.manager.api.permission.service.SysRoleService;
import com.wx.house.manager.api.permission.text.AdminRoleStateDto;
import com.wx.house.common.base.BaseController;
import com.wx.house.core.pojo.base.BasePage;
import com.wx.house.core.pojo.base.Result;
import com.wx.house.common.exception.BusinessException;
import com.wx.house.common.util.IDUtils;
import com.wx.house.common.util.JwtUtils;
import com.wx.house.common.util.StringUtil;
import com.wx.house.core.pojo.po.SysRole;

import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("SysRole/")
@Api(value = "角色模块", tags = "模块:角色管理")
@Slf4j
public class SysRoleController extends BaseController{
	@Resource
	private SysRoleService sysRoleService;
	
	@ApiOperation(value = "角色添加", notes = "角色添加")
	@PostMapping("addRole/")
	public Result addRole(@RequestBody @Validated RoleAddPame roleAddPame) {
		try {
			SysRole sysRole=SysRole.builder()
					.id(IDUtils.genItemId(8) + "")
					.roleName(roleAddPame.getRoleName())
					.remark(roleAddPame.getRemark())
					.maccType(Integer.valueOf(roleAddPame.getMaccType()))
					.creatTime(new Date())
					.state(0)
					.delType(0)
					.build();
			if(!StringUtil.isEmpty(roleAddPame.getRemark())) {
				sysRole.setRemark(roleAddPame.getRemark());
			}else {
				sysRole.setRemark(null);
			}
			sysRoleService.AddRole(sysRole);
			return Result.success();
		} catch (Exception e) {
			throw new BusinessException("添加失败");
		}
	}
	
	@ApiOperation(value = "查询全部角色", notes = "查询全部角色")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "roleName", value = "角色名(模糊)", required = false, dataType = "String", paramType = "query"),
		@ApiImplicitParam(name = "state", value = "状态", required = false, dataType = "String", paramType = "query")
	})
	@GetMapping("SelectRole/")
	public Result<PageInfo<SysRole>> SelectRole(String roleName,String state,BasePage page,HttpServletRequest request) {
		try {
			String token = request.getHeader("authorization");
			//step1. 解析token
			Claims claims = JwtUtils.builder().token(token).build().claims();
			//step2. 从token获取参数,获取账号类型
			String accoutype = claims.get("accountType").toString();
			List<SysRole> sysRoles=null;
			if("0".equals(accoutype)){
				 sysRoles=sysRoleService.selectRole(roleName, state, null);
			}else {
				 sysRoles=sysRoleService.selectRole(roleName, state, accoutype);
			}
			PageInfo<SysRole> pageInfo = new PageInfo<>(sysRoles);
			return Result.success(pageInfo);
		} catch (Exception e) {
			e.printStackTrace();
			throw new BusinessException("查询失败");
		}
	}
	
	@ApiOperation(value = "查询角色名是否存在", notes = "查询角色名是否存在")
	@GetMapping("getRoleName/")
	public Result getAdminName(String roleName) {
		try {
			SysRole role=	sysRoleService.getRoleName(roleName);
			if(StringUtil.isNotEmpty(role))
			{
				return Result.error(null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Result.success(null);
	}
	
	@ApiOperation(value = "更新角色", notes = "更新角色")
	@PutMapping("update/")
	public Result updateAdmin(@RequestBody @Validated RoleAddPame roleAddPame,HttpServletRequest request) {
		try {
			String token = request.getHeader("authorization");
			//step1. 解析token
			Claims claims = JwtUtils.builder().token(token).build().claims();
			//step2. 从token获取参数,获取账号等级
			String realName = claims.get("realName").toString();
			SysRole sysRole=new SysRole();
			//存入sysRole，判断是否有值
			sysRole.setId(roleAddPame.getRoleid());
			if (!StringUtils.isEmpty(roleAddPame.getRoleName()))
			{
				sysRole.setRoleName(roleAddPame.getRoleName());
			}
			if (!StringUtils.isEmpty(roleAddPame.getRemark()))
			{
				sysRole.setRemark(roleAddPame.getRemark());
			}
			if (!StringUtils.isEmpty(roleAddPame.getMaccType()))
			{
				sysRole.setMaccType(Integer.valueOf(roleAddPame.getMaccType()));
			}
			sysRole.setOperation(realName);
			sysRole.setOperationTime(new Date());
			sysRoleService.UpdateRole(sysRole);
			return Result.success();
		} catch (Exception e) {
			e.printStackTrace();
			if (false) throw new BusinessException("更新失败");
		}
		return Result.error("更新失败");
	}
	@ApiOperation(value = "禁用角色(禁用1/启用0)", notes = "禁用角色（传入的sysRoleId）")
	@PutMapping("delete/")
	public Result deleteAdmin(@RequestBody @Validated AdminRoleStateDto adminRoleStateDto) {
		try {
			if("0".equals(adminRoleStateDto.getState()))
			{
				sysRoleService.DeleteRole(adminRoleStateDto.getSysRoleId(), 0 );
			}
			if("1".equals(adminRoleStateDto.getState())) {
				sysRoleService.DeleteRole(adminRoleStateDto.getSysRoleId(), 1 );
			}
			return Result.success(null);
		} catch (Exception e) {
			throw new BusinessException("禁用/启用失败");
		}
	}
	@ApiOperation(value = "删除角色", notes = "删除角色（传入的sysRoleId）")
	@DeleteMapping("DeleteDelType/{sysRoleId}")
	public Result DeleteDelType(@PathVariable String sysRoleId) {
		try {
			sysRoleService.DeleteDelType(sysRoleId);
			return Result.success();
		} catch (Exception e) {
			throw new BusinessException("删除失败");
		}
	}
}